/*
 * Copyright 2008 Neil Bacon
 * Distributed under the terms of the Mozilla Public License version 1.1
 * or the GNU General Public License version 3.
 */

package nb.xadd.operator.impl;

import nb.xadd.node.Node;
import nb.xadd.operator.BinaryOperator;

/**
 * Key for cache of: (n1, binaryOperator, n2) -> result
 */
public class ApplyCacheKey {
    private final BinaryOperator binaryOperator;
    private final Node n1;
    private final Node n2;
    private final int hashCode;

    public ApplyCacheKey(BinaryOperator binaryOperator, Node n1, Node n2) {
        this.binaryOperator = binaryOperator;
        if (n1.compareTo(n2) <= 0) {
            this.n1 = n1;
            this.n2 = n2;
        } else {
            this.n1 = n2;
            this.n2 = n1;
        }
        this.hashCode = calcHashCode();
    }

    @Override
    public int hashCode() {
        return hashCode;
    }

    private int calcHashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + n1.hashCode();
        result = prime * result + n2.hashCode();
        result = prime * result + binaryOperator.hashCode();
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null || getClass() != obj.getClass())
            return false;
        ApplyCacheKey other = (ApplyCacheKey) obj;
        return n1 == other.n1 && n2 == other.n2 && binaryOperator == other.binaryOperator;
        // Only same objects are equal because Nodes are cached/interned
    }

}
